﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml.Linq;

namespace APIBetaSeries.Tools
{
    public class Requester
    {
        private static volatile Requester _instance;
        private static Object _syncRoot = new Object();

        private Requester()
        {
        }

        public static Requester Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                            _instance = new Requester();
                    }
                }
                return _instance;
            }
        }

        public XDocument SendMessage(String url, Dictionary<String, String> values)
        {
            XDocument xDocument = null;
            const string site = "http://api.betaseries.com/";
            String finalUrl = String.Concat(site, url);
            finalUrl += "?key=7FA8244D4A17";
            if (values != null)
                finalUrl = values.Aggregate(finalUrl, (current, value) => current + String.Format("&{0}={1}", value.Key, value.Value));
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(finalUrl);
            Stream stream = httpWebRequest.GetResponse().GetResponseStream();
            int i = 0;
            if (stream != null)
            {
                StreamReader reader = new StreamReader(stream);
                String sLine = "";
                String finalValue = String.Empty;
                while (sLine != null)
                {
                    i++;
                    sLine = reader.ReadLine();
                    if (sLine != null)
                        finalValue += sLine;
                }
                String file = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().FullName) + "xmlTemp.xml";
                File.WriteAllText(file, finalValue);
                xDocument = XDocument.Load(file);
                File.Delete(file);
            }
            return xDocument;
        }
    }
}
